# coding: utf-8

import os
import cv2
import base64
import json

from huaweicloudsdkcore.auth.credentials import BasicCredentials  # type: ignore
from huaweicloudsdkfrs.v2.region.frs_region import FrsRegion       # type: ignore
from huaweicloudsdkcore.exceptions import exceptions               # type: ignore
from huaweicloudsdkfrs.v2 import *                                 # type: ignore

nameDict = {
    "BZLe5blR": "陆李昕",
    "PAlzZkWo": "葛毅恒",
    "EOOuAs0o": "艾嘉豪",
    "pmp8TlnJ": "程一苓",
}

def parse_first_face_id_and_map_name(response):
    jsonobj = json.loads(str(response))
    first_face = jsonobj["faces"][0]
    face_id = first_face["face_id"]
    sim=first_face["similarity"]
    matched_name = nameDict.get(face_id, "未找到对应姓名")
    print(f"第一个人脸ID: {face_id}, 对应姓名: {matched_name}, 相似度: {sim}")
    return matched_name

def main():
    # 使用 OpenCV 从默认摄像头捕获图像
    cap = cv2.VideoCapture(0)  # 参数 0 表示打开默认摄像头
    ret, frame = cap.read()
    if not ret:
        print("无法从摄像头读取图像")
        cap.release()
        return "无法从摄像头读取图像"

    # 将捕获的图像保存为本地文件
    image_path = 'capture.png'
    cv2.imwrite(image_path, frame)
    cap.release()

    # 将保存的图像文件读取并转换为 Base64
    with open(image_path, 'rb') as f:
        base64str = base64.b64encode(f.read()).decode('utf-8')

    # 以下为调用华为云人脸搜索的示例
    # 仅供演示使用，使用前请配置好您的华为云 AK、SK，并在华为云控制台开通人脸识别服务
    ak = "NHYYVR32PAHNBFZRURPX"
    sk = "SlbMPJwmUQViEE9BeNK50BsteORqryR32EqjvGyh"

    credentials = BasicCredentials(ak, sk)
    client = FrsClient.new_builder() \
        .with_credentials(credentials) \
        .with_region(FrsRegion.value_of("cn-north-4")) \
        .build()

    try:
        request = SearchFaceByBase64Request()
        request.face_set_name = "ICT"  # 请更改为实际的人脸库名称
        request.body = FaceSearchBase64Req(
            image_base64=base64str
        )
        response = client.search_face_by_base64(request)
        return parse_first_face_id_and_map_name(response)
        
    except exceptions.ClientRequestException as e:
        print(e.status_code)
        print(e.request_id)
        print(e.error_code)
        print(e.error_msg)
        return "没有识别到人脸"

if __name__ == "__main__":
    main()

